package com.dhl.fin.api.service;

import com.dhl.fin.api.common.dto.QueryDto;
import com.dhl.fin.api.common.service.CommonService;
import com.dhl.fin.api.common.util.DateUtil;
import com.dhl.fin.api.common.util.ObjectUtil;
import com.dhl.fin.api.domain.BankAccount;
import com.dhl.fin.api.domain.BankCardMoneyReport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author CuiJianbo
 * @since 2025/4/9
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class BankCardMoneyReportService extends CommonService<BankCardMoneyReport> {

    @Autowired
    private BankAccountService bankAccountService;

    public void documentMoneyDataToReport() throws Exception {
        int month = DateUtil.getCurrentMonth();
        int year = DateUtil.getCurrentYear();

        List<BankAccount> bankAccounts = bankAccountService.getAllBankAccounts();
        for (BankAccount bankAccount : bankAccounts) {
            BankCardMoneyReport dbBankCardReport = findByBankAccountId(bankAccount.getId(), year, month);
            if (ObjectUtil.notNull(dbBankCardReport)) {
                dbBankCardReport.setCurrentBalance(bankAccount.getCurrentBalance());
                dbBankCardReport.setCurrentInterestIncome(bankAccount.getTotalInterestIncome());
                updateBySelective(dbBankCardReport);
            } else {
                BankCardMoneyReport bankCardMoneyReport = bankAccount.changeToReportData(year, month);
                saveOrUpdate(bankCardMoneyReport);
            }
        }

    }

    public BankCardMoneyReport findByBankAccountId(Long bankAccountId, int year, int month) throws Exception {
        return get(QueryDto.builder()
                .available()
                .addWhere("year = " + year)
                .addWhere("month = " + month)
                .addWhere("bank_account.id = " + bankAccountId)
                .build());
    }

    public List<BankCardMoneyReport> selectTotalIncomeByMonth(Long bankAccountId, String startDateStr) throws Exception {
        return select(QueryDto.builder()
                .available()
                .addWhere("year_month_date > '" + startDateStr + "'")
                .addWhere("bank_account_id = " + bankAccountId)
                .build());
    }

}
